<template>
	<div class="page-container">
		<h1>保质期计算器</h1>
		<el-form :model="form" label-width="120px">
			<el-form-item label="选择起始日期">
				<el-switch v-model="form.enableDate"></el-switch>
			</el-form-item>
			<el-form-item v-show="form.enableDate" label="起始日期">
				<el-date-picker v-model="form.startDate" type="date" placeholder="选择日期"></el-date-picker>
			</el-form-item>
			<el-form-item label="质保期限">
				<el-input-number v-model.number="form.expireDuration" :min="1" placeholder="请输入质保期限"></el-input-number>
				<el-select v-model="form.expireUnit" placeholder="请选择单位" style="width: 5rem;">
					<el-option v-for="unit in units" :key="unit.value" :value="unit.value" :label="unit.label">
					</el-option>
				</el-select>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" @click="calculateExpireDate">计算结束日期</el-button>
			</el-form-item>
		</el-form>
		<el-form label-width="120px">
			<el-form-item label="结束日期">
				<el-date-picker v-model="form.expireDate" type="date" readonly></el-date-picker>
			</el-form-item>
		</el-form>
		
	</div>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					enableDate: false,
					startDate: null,
					expireDuration: 30,
					expireUnit: 'day',
					expireDate: null
				},
				units: [{
						value: 'day',
						label: '天'
					},
					{
						value: 'week',
						label: '周'
					},
					{
						value: 'month',
						label: '月'
					}
				]
			};
		},
		methods: {
			calculateExpireDate() {
				const {
					enableDate,
					startDate,
					expireDuration,
					expireUnit
				} = this.form;

				let endDate;
				if (enableDate && startDate) {
					endDate = new Date(startDate);
				} else {
					endDate = new Date();
				}

				switch (expireUnit) {
					case 'day':
						endDate.setDate(endDate.getDate() + expireDuration);
						break;
					case 'week':
						endDate.setDate(endDate.getDate() + expireDuration * 7);
						break;
					case 'month':
						endDate.setMonth(endDate.getMonth() + expireDuration);
						break;
				}

				this.form.expireDate = endDate;
			}
		}
	};
</script>
